package alipay.openplatform.edu.campus.jiuye.api.filter;

import alipay.openplatform.edu.campus.jiuye.common.exception.OnlineRuntimeException;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常处理总控
 *
 * @author zhangyang
 * @create 2016-09-01
 */
@Component
public class BaseHandlerExceptionResolver implements HandlerExceptionResolver {
    private final static Logger logger = LoggerFactory.getLogger(BaseHandlerExceptionResolver.class);

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.error("", e);
        if (e instanceof OnlineRuntimeException) {
            PrintWriter pw = null;
            try {
                pw = response.getWriter();
            } catch (IOException e1) {
                logger.error("", e1);
            }
            OnlineRuntimeException exception = (OnlineRuntimeException) e;
            pw.write(JSON.toJSONString(ApiResult.build(exception.getCode(), e.getMessage())));
            pw.flush();
            pw.close();
            return null;
        }
        return new ModelAndView("front/error");
    }
}
